<?php

use Illuminate\Support\Facades\DB;

/**
 *
 * @author 李大牛家的牛 (scafel@163.com)
 * @className Helper.php
 * @createDate 2025/7/27 - 12:44
 * @description
 **/


function jsonReturn(int $code, string $msg, array $data = []): false|string
{
    $array = [
        'code' => $code,
        'msg' => $msg,
        'data' => empty($data) ? new StdClass() : $data,
    ];
    return json_encode($array, true);
}

function arrayReturn(int $code, string $msg, array $data = []): array
{
    return [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
}


/**
 * @param string $message
 * @functionName errorReturn
 * @creatTime 2019/9/30-10:01
 * @intention 错误内容返回
 */
function errorReturn(string $message = 'error', array $data = []): array|string {
    return ajaxReturn($data,$message,-1);
}

/**
 * @intention
 * @param string $message
 * @functionName successReturn
 * @creatTime 2020/3/11-11:12
 */
function successReturn(string $message = 'success', array $data = []): array|string
{
    return ajaxReturn($data,$message,1);
}

/**
 * Ajax方式返回数据到客户端
 * @access protected
 * @param mixed $data 要返回的数据
 * @param String $type AJAX返回数据格式
 * @param int $json_option 传递给json_encode的option参数
 * @return array|string
 */
function ajaxReturn(array $array,string $msg,int $code = 1,string $type=''): array|string {
    $data   =   array(
        'data'=>$array,
        'msg'=>$msg,
        'code'=>$code
    );
    //header("Access-Control-Allow-Origin: http://a.com"); // 允许a.com发起的跨域请求
    //如果需要设置允许所有域名发起的跨域请求，可以使用通配符 *
    header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
    header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
    if(empty($type)) $type  =   'json';
    switch (strtoupper($type)){
        case 'JSON' :
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            return $data;
        case 'XML'  :
            // 返回xml格式数据
            header('Content-Type:text/xml; charset=utf-8');
            return xmlEnCode($data);
        case 'EVAL' :
            // 返回可执行的js脚本
            header('Content-Type:text/html; charset=utf-8');
            return $data;
        default     :
            return $data;
    }
}

/**
 * CURL请求
 * @param string $url 请求url地址
 * @param string $method 请求方法 get post
 * @param array $postFields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug 调试开启 默认false
 * @return bool|string
 */
function httpRequest(string $url, string $method = "GET", array $postFields = array(), array $headers = array(), bool $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postFields)) {
                $tmpDataStr = http_build_query($postFields);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpDataStr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url);
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestInfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postFields);
        echo "=====info===== \r\n";
        print_r($requestInfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
}

/**
 * 验证表字段，并返回表拥有的字段
 * @param string $table 表名
 * @param array $input 输入的内容
 * @return array
 */
function createTableData(string $table, array $input): array
{
    //表字段
    $TableFields = getTableFields(config('database.connections.mysql.prefix') . $table);
    //过滤前数据
    $filter_data = $input;
    $data = [];
    foreach ($TableFields as $v) {
        $key    =   $v->COLUMN_NAME;
        foreach ($filter_data as $keys=>$vale){
            if ($key == $keys && $vale !== null){
                $data[$key] = $vale;
            }
        }
    }
    return empty($data)?[]:$data;
}

/**
 * 查询表字段
 * @param $table
 * @return array
 */
function getTableFields(string $table): array
{
    $sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '{$table}'";
    $message = DB::select($sql);
    return $message;
}
